import React from "react";
import { WeaDialog, WeaTop, WeaSteps, WeaNewScroll, WeaSearchGroup, WeaFormItem, WeaButtonIcon, 
  WeaLocaleProvider, WeaRightMenu, WeaInput, WeaUpload, WeaHelpfulTip, WeaInputSearch  } from "ecCom";
import { Button, Row, message, Modal, Icon, Tooltip } from 'antd';
import { inject, observer } from 'mobx-react';
import {WeaTableNew, WeaSwitch, WeaLogView} from 'comsMobx';
import { toJS } from 'mobx';
import NoRight from '../util/NoRight';
const {WeaTable} = WeaTableNew;
const Step = WeaSteps.Step;
const getLabel = WeaLocaleProvider.getLabel;
const WeaLogViewComp = WeaLogView.Component;
const store = [
  'weesoSeachSetStore',
  'weesoStore'
];
@inject(...store)
@observer
export default class WeesoSearchSet extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      weesoSearchPageSetHeight: 590,
    };
    this.customStepRef = React.createRef();
    this.customStepTopRef = React.createRef();
    this.weesoSearchPageSetRef = React.createRef();
  }

  componentDidMount() {
    const { getSeachTable, getSeachCustomTable, doSaveSearchTag, 
      doSaveHistorySearch, page_uuid
    } = this.props.weesoSeachSetStore;
    getSeachTable();
    getSeachCustomTable();
  }

  componentDidUpdate() {
    if(this.weesoSearchPageSetRef && this.weesoSearchPageSetRef.current && this.weesoSearchPageSetRef.current.state) {
      if(this.weesoSearchPageSetRef.current.state.height !== this.state.weesoSearchPageSetHeight) {
        this.setState({ weesoSearchPageSetHeight: this.weesoSearchPageSetRef.current.state.height });
      }
    }
  }

  openView = (page_uuid) => {
    if(page_uuid) {
      window.open(`/spa/esearch/static/index.html#/main/esearch/weeso?page_uuid=${page_uuid}`);
    }
  }

  onOperatesClick = (record,index,operate,flag, type) => {
    const { setState, getCusPageSetDtl, doSaveCusPageSetDtl, getCusPageSetList, delCusPageSet, getSearchTagDtl,
      search_type, delSearchTag, showAndHideSearchTag, getCustompageBaseDatas, recordParams 
    } = this.props.weesoSeachSetStore;

    if(type === 'searchSet') { // 搜索页面
      setState({ recordParams: record, commonPageType: '' });
      if(operate.index === '0') { // {getLabel('221','预览') }
        this.openView(record.page_uuid);
      } else if(operate.index === '1') { // 编辑
        setState({ customizationDialogVisible: true, recordId: record.randomFieldId, currentStep: 0, commonPageType: 'edit' }, () => {
          getCusPageSetDtl({
            id: record.randomFieldId,
            type: '1',
            page_uuid: record.page_uuid
          });
        });
      } else if(operate.index === '2') { // 另存为
        doSaveCusPageSetDtl({
          fromSaveAsNew: '1',
          id: record.randomFieldId,
        }, (ret) => {
          setState({ customizationDialogVisible: true, recordId: ret.newId, currentStep: 0, commonPageType: 'saveas', recordParams: { randomFieldId: ret.newId, page_uuid: ret.newPage_uuid } });
          getCusPageSetDtl({
            id: ret.newId,
            type: '1',
            page_uuid: ret.newPage_uuid
          });
          getCusPageSetList();
        });
      } else if(operate.index === '3') { // 删除
        this.delCusPageSet(record.randomFieldId);
      } else if(operate.index === '4') { // 日志
        setState({ logvisible: true });
      }
    } else if(type === 'searchCustom') { // 常用条件设置
      setState({ commonConditionParams: record });
      if(operate.index === '0') { // 编辑
        let p = {
          id: record.randomFieldId
        }
        if(!(this.props.page === 'maintenanceKey' && this.props.lvisible === true)) {
          p = {
            ...p,
            page_uuid: recordParams.page_uuid || ''
          }
        }
        getSearchTagDtl(p, () => {
          if(this.props.page === 'maintenanceKey' && this.props.lvisible === true) {
            setState({ maintenanceKeyAddCommonVisible: true, addRecordId: record.randomFieldId });
          } else {
            setState({ addCommonVisible: true, addRecordId: record.randomFieldId });
          }
          getCustompageBaseDatas({
            cuspage_type: '3'
          });
        });
      } else if(operate.index === '1') { // 隐藏 
        showAndHideSearchTag({ id: record.randomFieldId , enable: 0 }, () => {
          this.getCommonConditionSetTable();
          getCustompageBaseDatas({
            cuspage_type: '3'
          });
        });
      } else if(operate.index === '2') { // 取消隐藏
        showAndHideSearchTag({ id: record.randomFieldId , enable: 1 }, () => {
          this.getCommonConditionSetTable();
          getCustompageBaseDatas({
            cuspage_type: '3'
          });
        });
      } else if(operate.index === '3') { // 删除
        this.deleteRecords(getLabel(127574, '确定删除吗？'), () => {
          let p = {
            id: record.randomFieldId, 
          };
          if(this.props.page === 'maintenanceKey' && this.props.lvisible === true) {
          } else {
            p = {
              ...p,
              page_uuid: recordParams.page_uuid,
              fromSystem: 1, 
            };
          }
          delSearchTag(p, () => {
            this.getCommonConditionSetTable();
            getCustompageBaseDatas({
              cuspage_type: '3'
            });
          });
        },);
      }
    }
  }

  onTopBtnClick = (type) => {
    const { setState, customizationDialogVisible, getCusPageSetDtl, searchTableStore } = this.props.weesoSeachSetStore;
    if(type === 'add') {
      setState({ customizationDialogVisible: true, recordId: '', currentStep: 0, commonPageType: 'create', pageCusCurrentId: '' }, () => {
        getCusPageSetDtl({ type: '1' });
      });
    } else if(type === 'del') {
      this.delCusPageSet(toJS(searchTableStore.selectedRowKeys));
    }
  }

  delCusPageSet = (ids) => {
    const { getCusPageSetList, delCusPageSet } = this.props.weesoSeachSetStore;
    this.deleteRecords(getLabel(127574, '确定删除吗？'), () => {
      delCusPageSet({ id: ids }, () => {
        getCusPageSetList();
      });
    },);
  }

  copyUrl = (url) => {
    let mark = document.createElement('input');
   
    mark.value = url;
    document.body.appendChild(mark);
    mark.select();
    let successful = document.execCommand('Copy');
  
    if(successful) {
      message.success(getLabel('125245','复制成功'));
      mark && document.body.removeChild(mark);
    }
  }

  onFormItemChange = (formObj) => {
    let _this = this;
    const { setState } = this.props.weesoSeachSetStore;
    setState({ searchTagParams: {} });
    if(formObj.tagName) {
      if(window.esearch_debounce) clearTimeout(window.esearch_debounce);
      window.esearch_debounce = setTimeout(() => {// 防抖
        const { addCommonForm } = _this.props.weesoSeachSetStore;
        const formParams = addCommonForm.getFormParams();
        if(formParams.tagTitle === '' && formParams.tagName !== '') {
          addCommonForm.updateFields({ tagTitle: formParams.tagName });
        }
      }, 500);
    }
  }

  imgVisible = (domkey, type, imgValue) => {
    let uploadBool = false;
    if(domkey === 'page_resultLogo') {
      if(type === 'create' || type === 'create-edit') {
        if(imgValue === undefined || imgValue === '') {
          uploadBool = true;
        }
      } else {
        if(imgValue === undefined || imgValue === '') {
          uploadBool = true;
        }
      }
    } 
    if(domkey === 'page_icon') {
      if(type === 'create' || type === 'create-edit') {
        if(imgValue === undefined || imgValue === '') {
          if(type === 'create') {
            uploadBool = false;
          } else {
            uploadBool = true;
          }
        }
      } else {
        if(imgValue === undefined || imgValue === '') {
          uploadBool = true;
        }
      }
    } 
    return uploadBool;
  }

  imgV = (domkey, type, imgValue) => {
    let bool = true;
    if(domkey === 'page_icon') {
      if(imgValue === undefined || imgValue === '') {
        bool = false;
      } else if(imgValue === 'CLASSNAME:icon-coms-ws') {
        bool = false;
      }
    } 
    return bool;
  }

  resetDefaultIcon = () => {
    let { commonPageType,setState } = this.props.weesoSeachSetStore;
    setState({ commonPageType: 'create' });
  }

  getSearchs(form, conditioninfo, type) {
    let { currentStep, commonPageType, hasPageIcon, hasPageResultLogo, setState, page_icon_dir, recordParams } = this.props.weesoSeachSetStore;
    if(form === undefined || conditioninfo === undefined) return
    const { isFormInit } = form;
    const formParams = form.getFormParams();
    let group = [];
    let isstep2 = Number(currentStep) === 2;
    isFormInit &&
      toJS(conditioninfo).map((c, _index) => {
        let items = [];
        c.items.map(field => {
          let col = 1;
          if(type === 'viewUrl') {
            items.push({
              com: (
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@k2i1qo@${field.domkey[0]}`}
                  className={field.domkey ? field.domkey[0] : ''}
                  label={`${field.label}`}
                  labelCol={{ span: `${field.labelcol}` }}
                  ratio1to2
                  error={form.getError(field)}
                  tipPosition="bottom"
                  wrapperCol={{ span: `${field.fieldcol}` }}
                >
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@es0cqz@${field.domkey[0]}`} className="esearch-view-url-input" viewAttr={field.viewAttr} value={field.value} hasBorder />
                  <span className="esearch-view-url-icon" onClick={() => {
                    this.copyUrl(field.value);
                  }} >
                    <i className="icon-coms-copy"/>
                  </span>
                </WeaFormItem>
              ),
              col: col,
              hide: form.isHide(field, (keys, allParams) => {
               
                return false;
              })
            });
          } else {
            let pointPerson = false;
            if(field.domkey && field.domkey[0] === 'CREATERID_select' && formParams.CREATERID_select === '2') { // 创建人--指定人员
              field.selectLinkageDatas && field.selectLinkageDatas[2] && (field.selectLinkageDatas[2].viewAttr = 3);
              (formParams.CREATERID === '' || formParams.CREATERID === undefined) && (pointPerson = true);
            }
            if(type !== 'add-common-conditions') {
              if(field.domkey && (field.domkey[0] === 'WORKFLOWID' || field.domkey[0] === 'firstDirectory')) { // 流程-路径, 文档-目录必填
                field.viewAttr = 3;
              }
              if(field.domkey && field.domkey[0] === 'CREATEDATE_date_select' && formParams.CREATEDATE_date_select === '5') { // 创建时间--自定义
                field.selectLinkageDatas && field.selectLinkageDatas[5] && (field.selectLinkageDatas[5].viewAttr = 3);
              }
            }
            if(type === 'add-common-conditions') {
              if(field.domkey && field.domkey[0] === 'CREATEDATE_date_select' && formParams.CREATEDATE_date_select === '5') { // 创建时间--自定义
                field.selectLinkageDatas && field.selectLinkageDatas[5] && (field.selectLinkageDatas[5].viewAttr = 3);
              }
            }
            const deleteIcon = (
              <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@4ybvf8@deleteImg`} type="cross-circle-o" title={getLabel(16075, '删除图片')} domkey={field.domkey[0]} onClick={(e, ) => { 
                if(commonPageType === 'create') {
                  setState({ commonPageType: 'create-edit' });
                  if(e && e.target.getAttribute('domkey') === 'page_icon') {
                    form.updateFields({ page_icon: { value: '' } });
                  }
                  if(e && e.target.getAttribute('domkey') === 'page_resultLogo') {
                    form.updateFields({ page_resultLogo: { value: '' } });
                  }
                } else {
                  if(e && e.target.getAttribute('domkey') === 'page_icon') {
                    setState({ hasPageIcon: false });
                    form.updateFields({ page_icon: { value: '' } });
                  }
                  if(e && e.target.getAttribute('domkey') === 'page_resultLogo') {
                    setState({ hasPageResultLogo: false });
                    form.updateFields({ page_resultLogo: { value: '' } });
                  }
                }
              }} />
            );
            items.push({
              com: (
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@beij2y@${field.domkey[0]}`}
                  label={`${field.label}`}
                  labelCol={{ span: isstep2 ? 12 : `${field.labelcol}` }}
                  ratio1to2={!isstep2}
                  error={form.getError(field)}
                  tipPosition="bottom"
                  wrapperCol={{ span: isstep2 ? 12 : `${field.fieldcol}` }}
                  className={ field.domkey[0] === 'CREATERID_select' && pointPerson ? 'point-person':'' }
                >
                  { 
                    (field.domkey[0] === 'page_icon' || field.domkey[0] === 'page_resultLogo') ?
                      <div className='upload-img-area'>
                        { 
                          this.imgVisible(field.domkey[0], commonPageType, formParams[field.domkey[0]]) ? 
                            <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@4hgehn@${field.domkey[0]}`}
                              btnSize="small"
                              uploadUrl={field.uploadUrl}
                              category="string"
                              viewAttr={field.domkey[0] === 'page_resultLogo' ? 3: field.viewAttr}
                              isDetail={true}
                              editable={true}
                              showUploader={true}
                              showUploadTime={true}
                              uploadParams={{ test: 1 }}
                              clearWhenReset={false}
                              showClearAll={false}
                              showScan={true}
                              limitType="gif,bmp,png,jpg"
                              onChange={(ids, list) => {
                                form.updateFields({ [field.domkey[0]]: { value: ids[0] } });
                              }}
                            />
                          : 
                            <div className='img-area'>
                              { ((commonPageType === 'create' && field.domkey[0] === 'page_icon' && formParams.page_icon === '') || (field.domkey[0] === 'page_icon'&& formParams.page_icon === 'CLASSNAME:icon-coms-ws') ) && <span> 
                                  <i className='icon-coms-ws' />
                                  { deleteIcon }
                                </span>
                              }
                              
                              { !this.imgVisible(field.domkey[0], commonPageType, formParams[field.domkey[0]]) && this.imgV(field.domkey[0], commonPageType, formParams[field.domkey[0]]) && <span> 
                                  <img width={36} height={36} src={`${page_icon_dir}${formParams[field.domkey[0]]}`} /> 
                                  { deleteIcon }
                                </span>
                              }
                            </div>
                        }
                        {field.domkey[0] === 'page_icon' && <div className='img-area-desc'>{getLabel('524263','建议上传图片大小为36px*36px') }</div> }
                        {field.domkey[0] === 'page_resultLogo' && <div className='img-area-desc'>{getLabel('524264','建议上传图片大小为70px*40px')}</div> }
                        {recordParams.page_uuid === "FULLSEARCH" && field.domkey[0] === 'page_icon' && commonPageType !== 'create' && formParams.page_icon === '' && <div className='img-refresh'>
                          <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@niz9v2@tooltip`} title={getLabel('524372','恢复成默认图片')} onClick={this.resetDefaultIcon}>
                            <i className="icon-coms-Refresh" />
                          </Tooltip>
                        </div> }
                      </div>
                    :
                      <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@gy1vru@${field.domkey[0]}`} fieldConfig={field} form={form} onChange={this.onFormItemChange}/>
                  }
                  {
                    field.domkey[0] === 'page_descStr' && <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@dfji91@${field.domkey[0]}`}
                      className='img-page-descStr-tip'
                      width={230}
                      title={<div className='img-page_descStr'>
                        <span>{getLabel('524265','描述的位置说明') }</span>
                        <img width={219} height={94} src={require('../util/img/page_descStr.png')} />
                      </div>}
                      placement="bottomLeft"
                    />
                  }
                </WeaFormItem>
              ),
              col: col,
              hide: form.isHide(field, (keys, allParams) => {
                  let bool = true;
                  if(type === 'setpage') {
                    if(currentStep === 0) {
                      if(keys[0] === 'doc_sourceType') {// 文档来源
                        bool = false;
                        formParams['search_type'] === "DOC" && (bool = true);
                      }
                      if(keys[0] === 'firstDirectory') {// 目录
                        bool = false;
                        formParams['search_type'] === "DOC" && (bool = true);
                        formParams['doc_sourceType'] == '1' && (bool = false);

                      }
                      if(keys[0] === 'wf_sourceType') {// 流程来源
                        bool = false;
                        formParams['search_type'] === "WF" && (bool = true);
                      }
                      if(keys[0] === 'WORKFLOWID') {// 路径
                        bool = false;
                        formParams['search_type'] === "WF" && (bool = true);
                        formParams['wf_sourceType'] == '1' && (bool = false);
                      }
                      if(keys[0] === 'page_descStr') {// 描述
                        bool = true;
                        formParams['search_type'] === "ALL" && (bool = false);
                      }
                    }
                    if(currentStep === 2) {
                      keys[0] === "page_resultLogo" && formParams['page_resultShowLogo'] === "0" && (bool = false);
                    }
                  }

                return !bool;
              })
            });
          }
        });
        group.push(
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@zm9hah@${_index}`}
            className="esearch-group"
            needTigger={false}
            title={c.title}
            showGroup={c.defaultshow}
            items={items}
          />
        );
      });
    if(type === 'viewUrl') {
      group = <div className="weeso-search-add-common">{ group }</div>
    }
    return group;
  }

  stepOne = (callback) => {// 页面基本设置
    const { stepForm, doSaveCusPageSetDtl, setState, recordParams, currentStep, recordId } = this.props.weesoSeachSetStore;
    let formParams = stepForm.getFormParams();
    let current = parseInt(currentStep, 10);

    stepForm.validateForm().then(f => {
      if (f.isValid) {
        if((formParams.search_type === "WF" && formParams.wf_sourceType !== '1' && formParams.WORKFLOWID === '' )
          || (formParams.search_type === "DOC" && formParams.doc_sourceType !== '1' && formParams.firstDirectory === '' )
        ) {
          message.error(getLabel('524259','必填项未填写!') );
        } else {
          doSaveCusPageSetDtl({
            type: 1,
            id: recordId,
            page_uuid: recordParams.page_uuid,
            ...formParams
          }, (ret) => {
            setState({ recordParams: ret });
            typeof callback === 'function' && callback(ret);
          });
        }
      } else {
        f.showErrors();
      }
    });
  }

  stepThree = (callback) => {// 搜索结果页设置
    const { currentStep, setState, getCusPageSetDtl, recordId, stepForm, 
      doSaveCusPageSetDtl, recordParams
    } = this.props.weesoSeachSetStore;
    const formParams = stepForm.getFormParams();
    if(formParams.page_resultShowLogo == '1' && formParams.page_resultLogo === '') {
      message.error(getLabel('524259','必填项未填写!') );
    } else {
      stepForm.validateForm().then(f => {
        if (f.isValid) {
          doSaveCusPageSetDtl({
            type: 3,
            id: recordId,
            page_uuid: recordParams.page_uuid,
            ...formParams
          }, (ret) => {
            if(ret && ret.status === 'success') {
              typeof callback === 'function' && callback(ret);
            }
          });
        } else {
          f.showErrors();
        }
      });
    }
  }

  onStepClick = (type, btntype, callback) => {
    const { currentStep, setState, stepContents, getCusPageSetDtl, recordId, stepForm, 
      doSaveCusPageSetDtl, getCusPageSetList, recordParams, hasPageIcon, commonPageType
    } = this.props.weesoSeachSetStore;
    let current = parseInt(currentStep, 10);
    if(type === 'next-step' && currentStep < stepContents.length || btntype === 'viewBtn') {
      if(current === 0) { // 页面基本设置
        let formParams = stepForm.getFormParams();
        if(commonPageType === 'create') {//新建且没有点击过删除默认图片
          formParams = {
            ...formParams,
            page_icon: "CLASSNAME:icon-coms-ws",
          };
        }
        stepForm.validateForm().then(f => {
          if (f.isValid) {
            if((formParams.search_type === "WF" && formParams.wf_sourceType !== '1' && formParams.WORKFLOWID === '' )
              || (formParams.search_type === "DOC" && formParams.doc_sourceType !== '1' && formParams.firstDirectory === '' )
            ) {
              message.error(getLabel('524259','必填项未填写!') );
            } else {
              doSaveCusPageSetDtl({
                type: 1,
                id: recordId,
                page_uuid: recordParams.page_uuid,
                ...formParams
              }, (ret) => {
                if(btntype === 'viewBtn') {// 新建{getLabel('221','预览') }
                  typeof callback === 'function' && callback(recordParams.page_uuid);
                } else {
                  setState({ currentStep: current + 1, recordParams: ret});
                  this.getCommonConditionSetTable(ret);
                }
              });
            }
          } else {
            f.showErrors();
          }
        });
      } else if(current === 1) {
        getCusPageSetDtl({ id: recordId,type: current + 2, page_uuid: recordParams.page_uuid }, (ret) => {
          if(btntype === 'viewBtn') {
            typeof callback === 'function' && callback(recordParams.page_uuid);
          }else {
            setState({ currentStep: current + 1});
          }
        });
      } else if(current === 2) {// 搜索结果设置
        const formParams = stepForm.getFormParams();
        if(formParams.page_resultShowLogo == '1' && formParams.page_resultLogo === '') {
          message.error(getLabel('524259','必填项未填写!') );
        } else {
          stepForm.validateForm().then(f => {
            if (f.isValid) {
              doSaveCusPageSetDtl({
                type: 3,
                id: recordId,
                page_uuid: recordParams.page_uuid,
                ...formParams
              }, (ret) => {
                if(btntype === 'viewBtn') {
                  typeof callback === 'function' && callback(recordParams.page_uuid);
                }else {
                  setState({ currentStep: current + 1});
                  getCusPageSetDtl({ id: recordId,type: current + 2, page_uuid: ret.page_uuid });
                }
              });
            } else {
              f.showErrors();
            }
          });
        }
      } else if(current === 3) {
        if(btntype === 'viewBtn') {
          typeof callback === 'function' && callback(recordParams.page_uuid);
        }
      }
    } else if((type === 'pre-step' || type === 'click-step-pre')&& currentStep > 0) {
      if(current === 2 && (type !== 'click-step-pre')) {
        this.stepThree(() => {
          setState({ currentStep: current - 1});
          getCusPageSetDtl({ id: recordId,type: current, page_uuid: recordParams.page_uuid });
        });
      } else {
        setState({ currentStep: current - 1});
        getCusPageSetDtl({ id: recordId,type: current, page_uuid: recordParams.page_uuid });
      }
      this.getCommonConditionSetTable(recordParams);
    }

  }

  preStep = (type) => {
    if(type === 'click-step-pre') {
      this.onStepClick('click-step-pre');
    } else {
      this.onStepClick('pre-step');
    }
  }

  nextStep = () => {
    this.onStepClick('next-step');
  }

  viewBtn = () => {
    this.onStepClick('pre-step', 'viewBtn',this.openView);
  }

  getCommonConditionSetTable = (params) => {
    const { getSearchTagList, recordId, addRecordId } = this.props.weesoSeachSetStore;
    if(this.props.page === 'maintenanceKey' && this.props.lvisible === true) {
      getSearchTagList();
    } else {
      let p = {
        infoSetId: recordId, 
        fromSystem: 1
      };
      if(params && params.page_uuid) {
        p = {
          ...p,
          page_uuid: params.page_uuid
        }
      }
      getSearchTagList(p);
    }
  }

  stepComplete = () => {
    const { setState, getCusPageSetList } = this.props.weesoSeachSetStore;
    setState({ customizationDialogVisible: false });
    getCusPageSetList();
  }

  getCumtonDialogBtns = () => {
    const { currentStep, stepContents } = this.props.weesoSeachSetStore;
    let btns = [];
    let nextStep = false, preStep = false;
    if(currentStep > 0) {
      btns.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gmysai@preStep`} type="primary" disabled={preStep} key={'pre'} className="topbtn" onClick={this.preStep}>
          {getLabel('1876','上一步') }
        </Button>,
      );
    }
    if(currentStep < stepContents.length - 1) {
      btns.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4yo93q@nextStep`} type="primary" disabled={nextStep} key={'next'} className="topbtn" onClick={this.nextStep}>
          {getLabel('1402','下一步') }
        </Button>,
      );
    }
    if(currentStep === stepContents.length - 1) {
      btns.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ge5nh4@view`} type="primary" className="topbtn" key={'view'} onClick={this.viewBtn}>
          {getLabel('221','预览') }
        </Button>,
      );
      btns.push(
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@086b0m@complete`} type="primary" className="topbtn" key={'complete'} onClick={this.stepComplete}>
          {getLabel('555','完成') }
        </Button>,
      );
    }
    return btns;
  }

  getSearchDialogBtns = () => {
    let btns = [];
    btns.push(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1atsqv@searchsetSave`} type="primary" className="topbtn" key={'searchset-save'} onClick={() => {}}>
        {getLabel('555','完成') }
      </Button>,
    );
    
    return btns;
  }
  
  getRightMenu(btns) {
    let btnArr = [];
    Array.isArray(btns) && btns.forEach(res => {
      let icon = <i className="icon-coms02-preview" />;
      if(res.key === 'pre') {
        icon = <i className="icon-coms-Last-step" />;
      } else if(res.key === 'next') {
        icon = <i className="icon-coms-Next-step" />;
      } else if(res.key === 'searchset-save') {
        icon = <i className="icon-coms-Preservation" />;
      } else if(res.key === "complete") {
        icon = <i className="icon-coms-complete" />;
      } else if(res.key.indexOf('save') > -1) {
        icon = <i className="icon-coms-Preservation" />;
      }
      btnArr.push({
        key: res.key,
        icon: icon,
        content : res.props ? res.props.children : '',
        onClick : res.props ? res.props.onClick : null
      });
    }); 
    return btnArr;
  }

  filterParams = () => {
    let { browserKeyArr, addCommonForm } = this.props.weesoSeachSetStore;
    const formParams = addCommonForm.getFormParams();
    let search_json = { ...formParams };
    delete search_json.showorder;
    delete search_json.tagName;
    delete search_json.tagTitle;
    browserKeyArr = toJS(browserKeyArr);
    Object.keys(search_json).forEach(key => {
      if(browserKeyArr.some(v => v === key)) {
        if(search_json[key] !== '') {
          search_json[key] = search_json[key].split(',');
        } else {
          delete search_json[key];
        }
      }
    });
    return search_json;
  }

  addCommonSaveBtn = () => {
    const { addCommonForm, doSaveSearchTag, commonConditionParams, addRecordId, recordId,
      recordParams, getCustompageBaseDatas, editCommonConditionRetdatas
    } = this.props.weesoSeachSetStore;
    let { browserKeyArr } = this.props.weesoSeachSetStore;

    addCommonForm.validateForm().then(f => {
      if (f.isValid) {
        const formParams = addCommonForm.getFormParams();
        let bool = false;
        if(formParams.CREATEDATE_date_select === '5' &&(formParams.CREATEDATE_range_picker_end === '' || formParams.CREATEDATE_range_picker_end === undefined)) {
          bool = true;
        } 
        if(formParams.CREATERID_select === '2' &&(formParams.CREATERID === '' || formParams.CREATERID === undefined)) {
          bool = true;
        } 
        if(bool) {
          message.error(getLabel('524259','必填项未填写!') );
          return;
        }
        let search_json = { ...formParams };
        delete search_json.showorder;
        delete search_json.tagName;
        delete search_json.tagTitle;
        browserKeyArr = toJS(browserKeyArr);
        Object.keys(search_json).forEach(key => {
          if(browserKeyArr.some(v => v === key)) {
            if(search_json[key] !== '') {
              search_json[key] = search_json[key].split(',');
            } else {
              delete search_json[key];
            }
          }
        });
        let p = {
          ...formParams, 
          id: commonConditionParams.randomFieldId,
          search_json: JSON.stringify(search_json)
        };
        if(!(this.props.page === 'maintenanceKey' && this.props.lvisible === true)) {
          if(recordParams.page_uuid) {
            p = {
              ...p,
              fromSystem: 1,
              page_uuid: recordParams.page_uuid
            };
          } else {
            p = {
              ...p,
              fromSystem: 1,
            };
          }
        }
        if(editCommonConditionRetdatas.search_type) {
          p = {
            ...p,
            search_type: editCommonConditionRetdatas.search_type
          };
        }
        doSaveSearchTag({ ...p }, (ret) => {
          this.addCommononCancel();
          this.getCommonConditionSetTable(ret);
          getCustompageBaseDatas({
            cuspage_type: '3'
          });
        });
      } else {
        f.showErrors();
      }
    })
  }

  addCommonBtns = () => {
    let btns = [];
    btns.push(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7pe4x6@save`} type="primary" key={'save'} onClick={this.addCommonSaveBtn}>
        {getLabel('30986','保存') }
      </Button>,
    );

    return btns;
  }


  addCommononCancel = () => {
    const { setState } = this.props.weesoSeachSetStore;
    setState({ addCommonVisible: false, maintenanceKeyAddCommonVisible: false });
  }

  getAddCommonConditions = () => {
    const dialogW = 600, dialogH = 350;
    const { collectParams, addCommonVisible, maintenanceKeyAddCommonVisible, setState, addCommonForm, addCommonConditions } = this.props.weesoSeachSetStore;
    let dialogVisible = addCommonVisible;
    if(this.props.page === "maintenanceKey") {
      dialogVisible = maintenanceKeyAddCommonVisible;
    }
    return(<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@800rm4`} 
      className="weeso-search-add-common"
      visible={dialogVisible}
      title={getLabel('524266','添加常用条件') }
      icon={'icon-coms-ws'}
      iconBgcolor='#A0B0BA'
      style={{ width: dialogW, height: dialogH }}
      buttons={this.addCommonBtns()}
      onCancel={this.addCommononCancel}
      moreBtn={{
        datas : this.getRightMenu(this.addCommonBtns()),
        collectParams : collectParams
      }}
    >
      <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@h4p4je`}
        datas={this.getRightMenu(this.addCommonBtns())}
        collectParams={collectParams}
      >
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@avg8ek`} 
          className={'add-common-form'}
          height={dialogH}
        >
          { this.getSearchs(addCommonForm, addCommonConditions, 'add-common-conditions') }
        </WeaNewScroll>
      </WeaRightMenu>
    </WeaDialog>);
  }

  getUrlDialog = () => {
    const dialogW = 600, dialogH = 200;
    const { collectParams, urlDialogVisible, setState, stepForm, stepConditions } = this.props.weesoSeachSetStore;
    return(<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@jgticu`} 
      className="weeso-search-add-common"
      visible={urlDialogVisible}
      title={getLabel('524267','查看URL地址') }
      icon={'icon-coms-ws'}
      iconBgcolor='#A0B0BA'
      style={{ width: dialogW, height: dialogH }}
      // buttons={this.addCommonBtns()}
      onCancel={() => { setState({ urlDialogVisible: false }) }}
      // moreBtn={{
      //   datas : this.getRightMenu(this.addCommonBtns()),
      //   collectParams : collectParams
      // }}
    >
      { this.getSearchs(stepForm, stepConditions, 'viewUrl') }
    </WeaDialog>);
  }

  getColumns = (e) => {
    let newColumns = '';
    newColumns = e.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        return (
          newColumn.dataIndex == "page_uuid" ?
            <div className="wea-url-name" style={{cursor: 'pointer'}} onClick={() => {
              const { setState, getCusPageSetDtl } = this.props.weesoSeachSetStore;
              setState({ urlDialogVisible: true, recordId: record.randomFieldId });
              getCusPageSetDtl({ id: record.randomFieldId,type: '4' });
            }} dangerouslySetInnerHTML={{__html: getLabel('33564','查看')  }}/>
            :
            <div className="wea-url" dangerouslySetInnerHTML={{__html: valueSpan}}/>
        )
      }
      return newColumn;
    });
    return newColumns;
  }

  deleteRecords = (msg, onOk, onCancel) => {
    Modal.confirm({
      title: getLabel('131329','信息确认') ,
      content: msg,
      onOk() {
        typeof onOk === 'function' && onOk();
      },
      onCancel() {
        typeof onCancel === 'function' && onCancel();
      },
    });
  }

  maintenanceKeyAdd = () => {
    const { dialogVisible, setState, searchTableStore, customizationDialogVisible, form, conditions, currentStep,
      collectParams, stepForm, stepConditions, commonConditionTableStore, getSearchTagDtl, search_type, recordId,
      commonConditionParams,recordParams
    } = this.props.weesoSeachSetStore;
    let param = {};
    if(!(this.props.page === 'maintenanceKey' && this.props.lvisible === true)) {
      param = {
        page_uuid: recordParams.page_uuid,
      };
    }
    getSearchTagDtl({ id: '', ...param }, () => {
      if(this.props.page === 'maintenanceKey' && this.props.lvisible === true) {
        setState({ addCommonVisible: false, maintenanceKeyAddCommonVisible: true, commonConditionParams: {} });
      } else {
        setState({ addCommonVisible: true, maintenanceKeyAddCommonVisible: false, commonConditionParams: {} });
      }
    });
  }

  maintenanceKeyDel = () => {
    const { delSearchTag, commonConditionTableStore, recordI, recordParams, getCustompageBaseDatas } = this.props.weesoSeachSetStore;
    let ids = toJS(commonConditionTableStore.selectedRowKeys);
    let params = {
      id: ids, 
    };
    this.deleteRecords(getLabel(127574, '确定删除吗？'), () => {
      if(!(this.props.page === 'maintenanceKey' && this.props.lvisible === true)) {
        params = {
          ...params,
          page_uuid: recordParams.page_uuid,
          fromSystem: 1
        };
      }
      delSearchTag(params, () => {
        this.getCommonConditionSetTable();
        getCustompageBaseDatas({
          cuspage_type: '3'
        });
      });
    },);
  }

  searchPageCusCancel = () => {
    const { setState, commonPageType, pageCusCurrentId, delCusPageSet, currentStep } = this.props.weesoSeachSetStore;
    if(String(currentStep) === '1' || (String(currentStep) === '4' && commonPageType.indexOf('create') === -1 )) {
      setState({ customizationDialogVisible: false, recordParams: {} });
    } else {
      this.deleteRecords(getLabel('524268','数据未保存，确定退出吗？') ,() => {
        if(commonPageType === 'create' && pageCusCurrentId !== '') {
          delCusPageSet({ id: pageCusCurrentId }, () => {
            setState({ customizationDialogVisible: false, recordParams: {} });
          });
        } else {
          setState({ customizationDialogVisible: false, recordParams: {} });
        }
      });
    }
  }

  searchPageCancel = () => {
    
  }

  closeLog = () => {
    const { setState, } = this.props.weesoSeachSetStore;
    setState({ logvisible: false });
  }

  onSearch = (value) => {
    const { getCusPageSetList, setState } = this.props.weesoSeachSetStore;
    getCusPageSetList({ page_title: value || '' });
  }

  onSearchChange = (value) => {
    const { setState } = this.props.weesoSeachSetStore;
    setState({ searchDefinePageInputVal: value });
  }

  onCommonSearchChange = (value) => {
    const { setState } = this.props.weesoSeachSetStore;
    setState({ searchDefineCommonInputVal: value });
  }

  onCommonSearch = (value) => {
    const { getSearchTagList } = this.props.weesoSeachSetStore;
    getSearchTagList({ tagTitle: value || '' });
  }

  onCloseSearchDefineDialog = () => {
    const { setState } = this.props.weesoSeachSetStore;
    setState({ dialogVisible: false, searchDefineCommonInputVal: '', searchDefinePageInputVal: '' });
  }

  onStepChange = (e) => {
    if(e) {
      const { currentStep, setState, stepContents, getCusPageSetDtl, recordId, stepForm, 
        doSaveCusPageSetDtl, getCusPageSetList, recordParams, hasPageIcon, commonPageType
      } = this.props.weesoSeachSetStore;
      
      if(commonPageType !== 'saveas' && commonPageType !== 'edit') return;
      const current = Number(currentStep); // 当前步
      const now = Number(e.step);
      if(now > current) {// 往后
        if(current === 0) {
          this.stepOne((ret) => {
            setState({ currentStep: now });
            if(now === 1) {
              this.getCommonConditionSetTable(ret);
            }
            if(now === 2) {
              getCusPageSetDtl({ id: recordId,type: 3, page_uuid: recordParams.page_uuid }, (ret) => {
              });
            }
            if(now === 3) {
              getCusPageSetDtl({ id: recordId,type: 4, page_uuid: ret.page_uuid });
            }
          });
        }
        if(current === 1) {
          if(now === 2) {
            this.nextStep();
          }
          if(now === 3) {
            setState({ currentStep: now });
            getCusPageSetDtl({ id: recordId,type: 4, page_uuid: recordParams.page_uuid });
          }
        }
        if(current === 2) {
          this.nextStep();
        }
      }
      if(now < current) {// 往前
        if(current === 1) {
          this.preStep();
        }
        if(current === 2) {
          this.stepThree(() => {
            if(now === 0 ) {
              setState({ currentStep: now });
              getCusPageSetDtl({ id: recordId,type: 1, page_uuid: recordParams.page_uuid });
            }
            if(now === 1 ) {
              this.preStep('click-step-pre');
            }
          });
        }
        if(current === 3) {
          if(now === 0) {
            setState({ currentStep: now });
            getCusPageSetDtl({ id: recordId,type: 1, page_uuid: recordParams.page_uuid });
          }
          if(now === 1) {
            setState({ currentStep: now });
            this.getCommonConditionSetTable();
          }
          if(now === 2) {
            this.preStep();
          }
        }
      }
    }
  }

  render() {
    const { dialogVisible, setState, searchTableStore, customizationDialogVisible, form, conditions, currentStep,
      collectParams, stepForm, stepConditions, commonConditionTableStore, getSearchTagDtl, search_type,recordParams,
      logStore, logvisible, logSmallType, logType, searchPageRight, commonPageType
    } = this.props.weesoSeachSetStore;
    let { stepContents, } = this.props.weesoSeachSetStore;
    const { weesoSearchPageSetHeight } = this.state;
    stepContents = toJS(stepContents);
    const dialogH = weesoSearchPageSetHeight, dialogW = 900;
    const stepTopH = this.customStepTopRef&&this.customStepTopRef.current ? this.customStepTopRef.current.offsetHeight : 160;
    if(this.props.page === 'maintenanceKey') {
      return(<div className="weeso-search-set-container">
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@zavpq9`}
          className="customization-commonset"
          title=' '
          needTigger={false}
          showGroup={true}
          customComponent={
            <div className="commonset-btn-group">
              <span className="commonset-btn">
                <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@kbs0u5`} buttonType='add' type="primary" onClick={this.maintenanceKeyAdd} />
              </span>
              <span className="commonset-btn">
                <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@ekiwq0`} buttonType='del' type="primary" disabled={commonConditionTableStore.selectedRowKeys.length === 0} onClick={this.maintenanceKeyDel} />
              </span>
              <span className="commonset-btn">
                <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@8teyzj`}
                  onSearch={this.onCommonSearch}
                  onSearchChange={this.onCommonSearchChange}
                />
              </span>
            </div>
          }
        >
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@u82boj`}
            className="weeso-search-set-weatable"
            comsWeaTableStore={commonConditionTableStore}
            hasOrder={true}
            needScroll={true}
            scroll={{ y: this.props.dialogheight - 45 - 46 - 44 - 20 }}
            onOperatesClick={(record,index,operate,flag) => this.onOperatesClick(record,index,operate,flag, 'searchCustom')}
          />
        </WeaSearchGroup> 
        { this.getAddCommonConditions() }
      </div>)
    }

    return(<div className="weeso-search-set-container">
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@e0ngff`} 
        className="weeso-search-set"
        ref={this.weesoSearchPageSetRef}
        visible={dialogVisible}
        title={getLabel('523791','搜索页面定制') }
        icon={'icon-coms-ws'}
        iconBgcolor='#A0B0BA'
        style={{ width: dialogW, height: dialogH }}
        onCancel={this.onCloseSearchDefineDialog}
        // buttons={this.getSearchDialogBtns()}
        // moreBtn={{
        //   datas : this.getRightMenu(this.getSearchDialogBtns()),
        //   collectParams : collectParams
        // }}
      >
        {!searchPageRight && <NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@wyhtrn`} />}
        {searchPageRight && <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@xdzlum`}
          datas={this.getRightMenu()}
          collectParams={collectParams}
        >
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@69z48p`}
            className="weeso-search-set-topbtn"
            title=' '
            needTigger={false}
            showGroup={true}
            customComponent={
              <div className="topbtn-group">
                <span className="topbtn">
                  <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@o547p2`} buttonType='add' type="primary" onClick={() => {
                    this.onTopBtnClick("add");
                  }} />
                </span>
                <span className="topbtn">
                  <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@jcatm3`} buttonType='del' type="primary" disabled={searchTableStore.selectedRowKeys.length === 0} onClick={() => {
                    this.onTopBtnClick("del")
                  }} />
                </span>
                <span className="topbtn">
                  <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@8teyzj`}
                    onSearch={this.onSearch}
                    onSearchChange={this.onSearchChange}
                  />
                </span>
              </div>
            }
          >
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@arcfoh`}
              className="weeso-search-set-weatable"
              comsWeaTableStore={searchTableStore}
              hasOrder={true}
              needScroll={true}
              scroll={{ y: dialogH - 53 - 42 - 44 - 20 }}
              onOperatesClick={(record,index,operate,flag) => this.onOperatesClick(record,index,operate,flag, 'searchSet')}
              getColumns={this.getColumns}
            />
          </WeaSearchGroup>
        </WeaRightMenu>}
      </WeaDialog>

      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@hwf9x2`} 
        className="weeso-search-set-customization"
        visible={customizationDialogVisible}
        title={getLabel('523791','搜索页面定制') }
        icon={'icon-coms-ws'}
        iconBgcolor='#A0B0BA'
        style={{ width: dialogW, height: dialogH }}
        buttons={this.getCumtonDialogBtns()}
        onCancel={this.searchPageCusCancel}
        moreBtn={{
          datas : this.getRightMenu(this.getCumtonDialogBtns()),
          collectParams : collectParams
        }}
      >
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@og1mid`}
          datas={this.getRightMenu(this.getCumtonDialogBtns())}
          collectParams={collectParams}
        >
          <div ref={this.customStepTopRef} className={commonPageType}>
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@cxto7x`} className={'customization-step'} ref={this.customStepRef}>
              <WeaSteps ecId={`${this && this.props && this.props.ecId || ''}_WeaSteps@q7kkwk`}  current={currentStep}>
                {
                  stepContents && stepContents.map(res => (<Step ecId={`${this && this.props && this.props.ecId || ''}_Step@45vvw0@${currentStep}`} onClick={() => this.onStepChange(res)} description={res.label} />))
                }
              </WeaSteps>
            </Row>
          </div>
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@f0vi68`} 
            className={'customization-table'}
            height={ dialogH - stepTopH }
          >
            { currentStep !== 1 && currentStep !== 3 && this.getSearchs(stepForm, stepConditions, 'setpage') }
            { currentStep === 1 &&  <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@6qmj4e`}
              className="customization-commonset"
              title=' '
              needTigger={false}
              showGroup={true}
              customComponent={
                <div className="commonset-btn-group">
                  <span className="commonset-btn">
                    <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@95jlb2`} buttonType='add' type="primary" onClick={this.maintenanceKeyAdd} />
                  </span>
                  <span className="commonset-btn">
                    <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@bm8jlh`} buttonType='del' type="primary" disabled={commonConditionTableStore.selectedRowKeys.length === 0} onClick={this.maintenanceKeyDel} />
                  </span>
                </div>
              }
            >
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@8lbvzr`}
                className="weeso-search-set-weatable"
                comsWeaTableStore={commonConditionTableStore}
                hasOrder={true}
                needScroll={true}
                scroll={{ y: dialogH - stepTopH - 53 - 46 - 44 - 17 }}
                onOperatesClick={(record,index,operate,flag) => this.onOperatesClick(record,index,operate,flag, 'searchCustom')}
              />
            </WeaSearchGroup> }
            { currentStep === 3 && this.getSearchs(stepForm, stepConditions, 'viewUrl')}
          </WeaNewScroll>
        </WeaRightMenu>
      </WeaDialog>

      { this.getAddCommonConditions() }
      { this.getUrlDialog() }
      <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@gc5kjl`} targetId={recordParams.randomFieldId} visible={logvisible} onCancel={this.closeLog} logStore={logStore} logType={logType} logSmallType={logSmallType}/>
    </div>);
  }
}